package com.yueyang.sojourn.server.service.sojourn.collect;

import com.yueyang.sojourn.server.common.baymax.web.result.JAssert;
import com.yueyang.sojourn.server.model.enums.StatusEnum;
import com.yueyang.sojourn.server.model.po.SojournMerch;
import com.yueyang.sojourn.server.model.po.SojournMerchCollect;
import com.yueyang.sojourn.server.service.sojourn.merch.SojournMerchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author Stephen.Shi
 * @version v1
 * @summary 商品收藏service
 * @since 2020/2/20
 */
@Service
public class SojournMerchCollectService {
    @Autowired
    private SojournMerchCollectMapper collectMapper;
    @Autowired
    private SojournMerchService merchService;

    public SojournMerchCollect findById(Long id) {
        return this.collectMapper.selectByPrimaryKey(id);
    }

    /**
     * 收藏商品
     *
     * @param merchId
     * @param userId
     */
    public void collect(Long merchId, Long userId) {
        SojournMerch merch = merchService.selectByPrimaryKey(merchId);
        JAssert.pass(merch != null, "商品不存在");
        JAssert.pass(StatusEnum.VALID.getCode() == merch.getStatus(), "商品已下架");
        JAssert.pass(findByMerchIdAndUserId(merchId, userId) == null, "已经收藏过了");
        SojournMerchCollect collect = new SojournMerchCollect();
        collect.setMerchId(merchId);
        collect.setUserId(userId);
        collect.setCtime(new Date());
        this.collectMapper.insert(collect);
    }

    public SojournMerchCollect findByMerchIdAndUserId(Long merchId, Long userId) {
        SojournMerchCollectExample example = new SojournMerchCollectExample();
        example.createCriteria().andMerchIdEqualTo(merchId).andUserIdEqualTo(userId);
        return this.collectMapper.selectByExample(example).stream().findFirst().orElse(null);
    }

    /**
     * 取消收藏商品
     */
    public void cancelCollect(Long merchId, Long userId) {
        SojournMerchCollect collect = this.findByMerchIdAndUserId(merchId, userId);
        // 考虑到此操作具备幂等性，如果不存在 不需要报错
        if (collect != null) {
            this.delete(collect.getId());
        }
    }

    public void delete(Long id) {
        this.collectMapper.deleteByPrimaryKey(id);
    }

}
